import socket
import threading

def web_thr(new_socket, ip_port):
        recv_data = new_socket.recv(4096)
        if len(recv_data) == 0:
            new_socket.close()
            return
        # 对二进制进行解码
        recv_content = recv_data.decode('utf-8')
        request_list = recv_content.split(" ", 2)
        request_path = request_list[1]
        print(request_path)
        # 判断请求是否是根目录，是根，就返回index.html
        if request_path == "/":
            request_path = '/index.html'
        # 为了兼容图片，需要用二进制方式打开“rb”
        #1.判断文件是否存在 os.path.exists("static"+request_path)
        #2.try去捕获
        try:
            with open(f'./static{request_path}', 'rb') as file:
                file_data = file.read()
        except Exception as e:
            # 响应行----
            response_line = "HTTP/1.1 404 Not Found\r\n"
            # 响应头
            response_head = "Server:Pws/1.0\r\n"
            with open('static/error.html','rb') as file:
                file_data=file.read()
            response_body = file_data
            #因为响应体已经的是二进制，所以只需要把请求行和请求头，一起转码成二进制就行了
            response = (response_line +
                        response_head +
                        "\r\n").encode('utf-8') + response_body
            new_socket.send(response)

        else:
            # 封装
            # 响应行----
            response_line = "HTTP/1.1 200 OK\r\n"
            # 响应头
            response_head = "Server:Pws/1.0\r\n"
            # 响应体
            response_body = file_data
            #因为响应体已经的是二进制，所以只需要把请求行和请求头，一起转码成二进制就行了
            response = (response_line +
                        response_head +
                        "\r\n").encode('utf-8') + response_body
            new_socket.send(response)
        finally:
            new_socket.close()

if __name__ == '__main__':
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    tcp_server_socket.bind(('', 8000))
    tcp_server_socket.listen(128)
    while True:
        new_socket, ip_port = tcp_server_socket.accept()
        custom_thr=threading.Thread(target=web_thr,args=(new_socket, ip_port),daemon=True)
        print(custom_thr)
        custom_thr.start()
    tcp_server_socket.close()